import { useNavigate, useParams } from "react-router-dom";
import { ResBody, request } from "../common/request";
import { useAsync, useMount, useSetState } from "react-use";
import { useEffect, useRef } from "react";
import {
  FileModel,
  GoodsModel,
  OrderModel,
  CommentModel,
} from "../common/model";
import { PreviewCard } from "../components/PreviewCard";
import { clsx, toUrlFromVideo } from "../common/utils";
import {
  App,
  Avatar,
  Button,
  Input,
  List,
  Modal,
  QRCode,
  Space,
  Spin,
  Tag,
} from "antd";
import { Play, Lock, Chat, XCicle, Collect, Like } from "../components/Icon";
import { useAuthStore } from "../store/auth";
import { DefaultAvatar, dayjs } from "../common/constant";
import { ExclamationCircleFilled } from "@ant-design/icons";
import { TextAreaRef } from "antd/es/input/TextArea";
import { useSystemStore } from "../store/system";

const GoodsId: React.FC = () => {
  const { gid } = useParams();
  const auth = useAuthStore();
  const system = useSystemStore();
  const { modal } = App.useApp();
  const commentRef = useRef<TextAreaRef>(null);
  const [state, setState] = useSetState({
    data: undefined as undefined | GoodsModel, //商品详情
    loading: false, //商品详情加载
    previewList: [] as string[], // 商品列表预览图
    buyModalOpen: false, //支付弹窗
    orderInfo: undefined as undefined | OrderModel, //订单详情
    previewFile: undefined as undefined | FileModel, //当前点击预览文件
  });
  const navigate = useNavigate();
  const [comment, setComment] = useSetState({
    current: "", //当前评论
    list: [] as CommentModel[], //评论列表
    page: 1,
    total: -1,
    placeholder: "发表评论",
    reply: undefined as
      | undefined
      | {
          parent_id: number;
          to_uid: number | null;
          name: string;
        }, //回复对象
  });

  const onDeleteComment = async (id: number) => {
    modal.confirm({
      centered: true,
      title: "你确定要删除吗?",
      icon: <ExclamationCircleFilled />,
      content: "删除后将不可恢复",
      okText: "确认",
      cancelText: "取消",
      maskClosable: true,
      async onOk() {
        const ret = await request.delete<any, ResBody>(
          `/api/comment/delete/${id}`
        );
        if (ret.code === 200) {
          system.message("success", ret.msg);
          loadComments(true);
        }
      },
    });
  };

  const loadComments = async (first?: boolean) => {
    if (!first && comment.total === comment.list.length) {
      return system.message("error", "没有了");
    }
    const page = first ? 1 : comment.page + 1;
    const ret = await request.get<any, ResBody>(`api/comment/query`, {
      params: { gid, page, page_size: 10 },
    });
    // console.log(ret);
    if (ret.code === 200) {
      setComment({
        list: first ? ret.result : comment.list.concat(ret.result),
        total: ret.total,
        page,
      });
    }
  };

  useEffect(() => {
    loadGoodsInfo();
  }, [auth.user]);

  const onComment = async () => {
    if (!auth.user) {
      return system.message("warning", "请先登录，才能评论！");
    }
    if (!comment.current) return;
    const ret = await request.post<any, ResBody>("/api/comment/create", {
      gid: state.data?.id,
      content: comment.current,
      parent_id: comment.reply?.parent_id ?? null,
      to_uid: comment.reply?.to_uid ?? null,
    });
    if (ret.code === 200) {
      system.message("success", ret.msg);
      loadComments(true);
      setComment({ current: "", reply: undefined });
    }
  };

  const loadGoodsInfo = async () => {
    setState({ loading: true });
    const ret = await request.get<any, ResBody>(`/api/goods/detail/${gid}`);
    setState({ loading: false });
    // console.log(ret);
    if (ret.code === 200) {
      setState({ data: ret.goods });
    }
  };

  useMount(() => {
    loadComments(true);
  });

  useAsync(async () => {
    if (state.data?.files) {
      const previewList = await Promise.all(
        state.data.files.map(async (f) => {
          if (f.type.includes("video")) {
            return await toUrlFromVideo(f.url);
          } else {
            return f.url;
          }
        })
      );
      setState({ previewList });
    }
  }, [state.data]);

  const onPuy = async () => {
    //提交支付
    const ret = await request.post<ResBody>(
      "/api/order/paid",
      JSON.stringify({ order_id: state.orderInfo?.id })
    );
    if (ret.data.code === 200) {
      system.message("success", "支付成功");
      setState({ buyModalOpen: false });
      loadGoodsInfo();
    }
  };

  const afterOpenChange = async (open: boolean) => {
    if (open) {
      //创建订单
      if (state.orderInfo) {
        return;
      }
      const ret = await request.post<ResBody>(
        "/api/order/create",
        JSON.stringify({
          gid: state.data?.id,
          amount: state.data?.price,
          g_uid: state.data?.uid,
        })
      );

      // console.log(ret);
      if (ret.data.code === 200) {
        setState({ orderInfo: ret.data.result });
      } else if (ret.data.err) {
        // system.message("error", ret.err);
      }
    }
  };

  const handleLike = async (type: "like" | "collect") => {
    const url =
      type === "like"
        ? "/api/relation/switch-like/"
        : "/api/relation/switch-collect/";
    const ret = await request.post<any, ResBody>(url + state.data?.id);
    if (ret.code === 200) {
      system.message("success", ret.msg);
      loadGoodsInfo();
    }
  };

  return (
    <div className="max-w-xl">
      <Modal
        open={state.buyModalOpen}
        title={state.data?.title}
        footer={null}
        centered
        width={300}
        afterOpenChange={afterOpenChange}
        onCancel={() => setState({ buyModalOpen: false })}
      >
        {state.orderInfo ? (
          <>
            {/* <QRCode value={"https://reactjs.org/"} size={100} /> */}
            <QRCode size={120} errorLevel="H" value="https://reactjs.org/" />
            <div className="mt-2 text-font2 mb-2">
              请使用微信支付，你需要支付{state.data?.price}
            </div>
            <Button type="primary" onClick={onPuy}>
              确认支付
            </Button>
          </>
        ) : (
          "正在创建订单..."
        )}
      </Modal>
      <Spin spinning={state.loading}>
        {state.data && (
          <>
            {state.data.preview.length > 0 && (
              <PreviewCard images={state.data.preview} />
            )}
            <div className="flex items-center py-2 text-font2 text-lg">
              <Avatar
                size={28}
                className="border-none cursor-pointer"
                src={
                  <img
                    src={
                      state.data.user?.avatar
                        ? state.data.user.avatar
                        : DefaultAvatar
                    }
                    alt=""
                  />
                }
              />
              <div className="ml-1 cursor-pointer">
                {state.data.user?.nickname}
              </div>
              <Button
                type="primary"
                shape="round"
                className=" !bg-active font-bold ml-2 h-7 py-0 !px-3"
                onClick={() => {
                  navigate(-1);
                }}
              >
                关注
              </Button>
              <div className="flex-1" />
              <div>
                {dayjs(state.data.create_at).format("YYYY/MM/DD HH:mm:ss")}
              </div>
            </div>
            <div className="text-2xl font-bold my-2">{state.data.title}</div>
            <div className="mb-2 whitespace-pre-line">{state.data.intro}</div>
            <Space size={[0, 8]} wrap className="mb-2">
              {state.data.tags.map((t, key) => (
                <Tag color="orange" key={key}>
                  {t}
                </Tag>
              ))}
            </Space>
            {state.data.locked && (
              <div
                className={clsx(
                  "flex items-center h-40 border justify-center",
                  "cursor-pointer flex-col text-font2 border-dashed",
                  "bg-grey2 rounded-md"
                )}
                onClick={() => setState({ buyModalOpen: true })}
              >
                <Lock size={50} />
                <span className="font-bold">¥{state.data.price}元</span>
              </div>
            )}
            <div className="border border-grey border-b-0">
              {state.data.files?.map((f, key) => (
                <div
                  className={clsx(
                    "cursor-pointer relative border-b border-grey",
                    "rounded-sm p-2 flex items-center"
                  )}
                  key={f.uid}
                  onClick={() => {
                    setState({ previewFile: f });
                  }}
                >
                  {f.type.includes("video") && (
                    <Play className="text-white absolute left-7 z-10" />
                  )}
                  <img
                    src={state.previewList[key]}
                    alt=""
                    className="object-cover w-16 h-16 mr-2 rounded-sm"
                  />
                  <div className="flex-1 truncate">{f.name}</div>
                </div>
              ))}
            </div>
            <div className="flex items-center mt-6 space-x-2">
              <Like
                size={26}
                className="cursor-pointer"
                liked={!!state.data.liked_id}
                onClick={() => handleLike("like")}
              />
              <Collect
                className="cursor-pointer"
                collected={!!state.data.collected_id}
                onClick={() => handleLike("collect")}
              />
              <Chat
                className="cursor-pointer"
                onClick={() => {
                  setComment({ reply: undefined });
                  commentRef.current?.focus();
                }}
              />
            </div>
            <div className="flex items-center mt-2">
              <Input.TextArea
                ref={commentRef}
                placeholder={
                  comment.reply ? `回复 @${comment.reply.name}` : "发表评论"
                }
                value={comment.current}
                className={clsx(
                  "!border !border-[#d9d9d9] flex-1 !resize-none",
                  { "rounded-r-none": !!comment.current }
                )}
                onChange={(evt) => setComment({ current: evt.target.value })}
              />
              <Button
                type="primary"
                className={clsx(
                  "w-14 !h-14 rounded-l-none font-bold transition-[width]",
                  { "!w-0": !comment.current },
                  "overflow-visible px-0 border-none",
                  "overflow-hidden"
                )}
                onClick={onComment}
              >
                发表
              </Button>
            </div>
            <List
              className="mt-2"
              bordered={false}
              size="small"
              locale={{ emptyText: "暂无评论" }}
              dataSource={comment.list}
              loadMore={
                comment.total > comment.list.length ? (
                  <div className="text-center">
                    <Button
                      type="text"
                      className="font-bold text-font2"
                      onClick={() => loadComments()}
                    >
                      加载更多
                    </Button>
                  </div>
                ) : null
              }
              renderItem={(item) => (
                <List.Item className="!block !px-1">
                  <div className="flex items-center text-font2 mb-1">
                    <Avatar
                      size={26}
                      className="cursor-pointer"
                      src={<img src={item.user.avatar ?? DefaultAvatar} />}
                    />
                    <div className="cursor-pointer text-sm ml-1">
                      {item.user.nickname}
                    </div>
                    <div className="text-sm ml-2">
                      {dayjs(item.create_at).fromNow()}
                    </div>
                    <div className="flex-1" />
                    <XCicle
                      className="cursor-pointer mr-3"
                      size={22}
                      onClick={() => onDeleteComment(item.id)}
                    />
                    <Chat
                      className="cursor-pointer"
                      size={22}
                      onClick={() => {
                        item;
                        setComment({
                          reply: {
                            parent_id: item.id,
                            to_uid: item.userId,
                            name: item.user.nickname,
                          },
                        });
                        commentRef.current?.focus();
                      }}
                    />
                  </div>
                  <div className="text-lg">{item.content}</div>
                  {item.replys?.length > 0 && (
                    <List
                      dataSource={item.replys}
                      size="small"
                      renderItem={(citem) => (
                        <List.Item className="!block !border-none !pr-1">
                          <div className="flex items-center text-font2 mb-1">
                            <Avatar
                              size={20}
                              className="cursor-pointer"
                              src={
                                <img
                                  alt=""
                                  src={citem.user.avatar ?? DefaultAvatar}
                                />
                              }
                            />
                            <div className="cursor-pointer text-xs ml-1">
                              {citem.user.nickname}
                            </div>
                            <div className="text-xs ml-2">
                              {dayjs(citem.create_at).fromNow()}
                            </div>
                            <div className="flex-1" />
                            <XCicle
                              className="cursor-pointer mr-2"
                              size={18}
                              onClick={() => onDeleteComment(citem.id)}
                            />
                            <Chat
                              className="cursor-pointer"
                              size={18}
                              onClick={() => {
                                setComment({
                                  reply: {
                                    parent_id: item.id,
                                    to_uid: citem.user.id,
                                    name: citem.user.nickname,
                                  },
                                });
                                commentRef.current?.focus();
                              }}
                            />
                          </div>
                          <div className="">
                            {citem.toUser?.id && (
                              <span className="text-font2 mr-1">
                                回复@{citem.toUser.nickname}
                              </span>
                            )}
                            {citem.content}
                          </div>
                        </List.Item>
                      )}
                    />
                  )}
                </List.Item>
              )}
            />
            <Modal
              open={!!state.previewFile}
              title={state.previewFile?.name}
              footer={null}
              centered
              destroyOnClose
              width={800}
              onCancel={() => setState({ previewFile: undefined })}
              bodyStyle={{ textAlign: "center" }}
            >
              {state.previewFile?.type.includes("image") ? (
                <img alt="" className="inline" src={state.previewFile.url} />
              ) : state.previewFile?.type.includes("video") ? (
                <video
                  className="w-full"
                  src={state.previewFile.url}
                  controls
                ></video>
              ) : null}
            </Modal>
          </>
        )}
      </Spin>
    </div>
  );
};

export default GoodsId;
